package web;

import com.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import pojo.user;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import static util.factory.getFactory;

@WebServlet(value = "/loginServlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//        接收用户名密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

//调用mybatis完成查询


//      获取sqlSessionFactory对象
        /*
        String resource = "mybatis-config.xml";//这里记得修改,mybatis官网中可以找到这段代码
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        */
        SqlSessionFactory factory = getFactory();   //这句为优化的代码，替换上面的

//        获取sqlSession对象
        SqlSession sqlSession = factory.openSession();      //这里代表着与数据库的连接，每次都创建一
        // 个新的，相当于线程工厂的一个线程
//        获取mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        调用方法查找
        user se = mapper.select(username, password);
//        释放资源
        sqlSession.close();

        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        res.setContentType("text/html;charset=utf-8");     //修改编码
//        假如查询不为空，即数据库中有对应的name和password
        if(se!=null)
        {
            writer.write("<h1>登录成功</h1>");
        }else{
            writer.write("<h1>登录失败<h1>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        this.doGet(req, res);
    }
}
